package com.loren.oauth.web.controller;

import com.loren.oauth.data.constant.DataConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Controller
@AllArgsConstructor
public class OAuthController {

    private final RequestCache requestCache = new HttpSessionRequestCache();

    @GetMapping(DataConstant.AUTH_LOGIN_URL)
    public String connectAuthorize(HttpServletRequest request, HttpServletResponse response) {
        SavedRequest savedRequest = requestCache.getRequest(request, response);
        // 如果没有包含重定向的链接，返回 404 页面
        if (savedRequest == null || StringUtils.isBlank(savedRequest.getRedirectUrl())) {
            return "error/not-found";
        }
        String redirectUrl = savedRequest.getRedirectUrl();
        String requestUri = StringUtils.substring(redirectUrl, 0, StringUtils.indexOf(redirectUrl, "?"));
        // 如果重定向的链接没有'?' 或者 不是从 /oauth/authorize 重定向过来的，返回 404 页面
        if (!StringUtils.contains(redirectUrl, "?") || !StringUtils.endsWith(requestUri, "/oauth/authorize")) {
            return "error/not-found";
        }
//        Map<String, String[]> parameterMap = savedRequest.getParameterMap();
//        String clientId = parameterMap.get("client_id")[0];
//        String redirectUri = parameterMap.get("redirect_uri")[0];
//        String responseType = parameterMap.get("response_type")[0];
//        log.info("clientId = {}, redirectUri = {}, responseType = {}", clientId, redirectUri, responseType);
        Object errorObject = request.getSession().getAttribute(DataConstant.ERROR_LOGIN_FLAG);
        if (errorObject != null) {
            String errorMessage = (String) errorObject;
            request.getSession().removeAttribute(DataConstant.ERROR_LOGIN_FLAG);
            request.setAttribute(DataConstant.ERROR_LOGIN_FLAG, errorMessage);
            return "oauth-login";
        }
        return "oauth-login";
    }
}
